﻿var messageTimeout = 1500;
var searchDelay = 1000;
var errorLabel = '<b>Error</b>: ';
var ForceChangePassword = false;
varSelect = { id: "0", text: "Select" };
var vRequest = 0, vResponse = 1;
var m_vValidationMessage = 'Kindly make sure all data is entered correctly.'
var m_CallBackWindowScrollPosition = 0;

////@@@ universal value for select 2 dropdown type used at different places.
var m_DropdownUsedFor = {
    ADD: 1,
    EDIT: 2,
    SEARCH: 3
};

/// Creating JSON FORMAT to be passed as compulsory parameter for every select 2 dropdown.
var ddl_ADD = 'ddlUsedFor@@' + m_DropdownUsedFor.ADD;
var ddl_EDIT = 'ddlUsedFor@@' + m_DropdownUsedFor.EDIT;
var ddl_SEARCH = 'ddlUsedFor@@' + m_DropdownUsedFor.SEARCH;

var m_SaveMessage = "XXX details saved successfully.";
var m_SaveErrorMessage = "XXX details could not be saved.";
var m_SubmitMessage = "XXX details submitted successfully.";
var m_SubmitErrorMessage = "XXX details could not be submitted.";
var m_UpdateMessage = "XXX details updated successfully.";
var m_UpdateErrorMessage = "XXX details could not be updated.";
var m_ExistMessage = "XXX already exists.";
var m_CancelMessage = "XXX canceled successfully.";
var m_CancelErrorMessage = "XXX could not be canceled.";
var m_ActivationMessage = "XXX status activated successfully.";
var m_ActivationErrorMessage = "XXX status could not be activated.";
var m_InactivationMessage = "XXX status inactivated successfully.";
var m_InactivationErrorMessage = "XXX status could not be inactivated.";
var m_DeleteMessage = "XXX details deleted successfully.";
var m_DeleteErrorMessage = "XXX details could not be deleted.";

$(window).resize(function () {
    var ht = $(window).height() / 2 - $('#fixdiv').height() / 2 + 'px';
    var wt = $(window).width() / 2 - $('#fixdiv').width() / 2 + 'px';
    $('#fixdiv').css({ top: ht });
    $('#fixdiv').css({ left: wt });


});

function On_WindowResize(p_TargerDiv) {
    var divID = '#' + p_TargerDiv;
    var ht = $(window).height() / 2 - $(divID).height() / 2 + 'px';
    var wt = $(window).width() / 2 - $(divID).width() / 2 + 'px';
    $(divID).css({ top: ht });
    $(divID).css({ left: wt });
}

function callBack(track, controlList, additionalTracks) {
    fn_GetScrollPostion();
    var args = '';
    args = CreateJsonString(track, controlList, additionalTracks); //.replace("<p>","").replace("</p>", "");
    show_processing();
    UseCallback(args);
}

function masterCallBack(track, controlList, additionalTracks) {
    var args = '';
    args = CreateJsonString(track, controlList, additionalTracks); //.replace("<p>","").replace("</p>", "");
    show_processing();
    MasterUseCallback(args);
}

function controlCallBack(callBackFunction, track, controlList, additionalTracks) {
    var args = '';
    args = CreateJsonString(track, controlList, additionalTracks); //.replace("<p>","").replace("</p>", "");
    show_processing();
    window[callBackFunction](args);
}

function show_processing() {
    fn_ShowDiv('fixdiv');

}

function hideLoader(returnVal) {
    fn_HideDiv('fixdiv');
    if (isNULL(returnVal) == '') {
        throw 'Blank returnVal';
    }
}
function CreateJsonString(Track, ControlList, AdditionalTracks) {
    /// <summary>
    /// Sends a callback request to server in the form of Json .
    /// </summary>
    /// <param name="Track">String representing purpose of callback like CREATE,EDIT,DELETE etc</param>
    /// <param name="ControlList">@ Separated list of ControlNames whoes values needs to be passed to server</param> b
    /// <param name="Pageurl">Url of the Server Page </param>
    /// <param name="ResponseFunctionName">Function which will process data returned by server</param>
    /// <param name="AdditionalTracks">@@ and ~~ separated string for passing additional data to server</param>

    var ArrID;

    var jsontext = '{';

    jsontext = jsontext + '"Track":"' + Track + '",';

    if (isNULL(ControlList) != '') {

        var rowArr = new Array();

        if (ControlList.indexOf('@') == -1) {
            rowArr.push(ControlList);
        }
        else {
            rowArr = ControlList.split('@');
        }

        for (i = 0; i < rowArr.length; i++) {

            if (document.getElementById(rowArr[i]).type == 'checkbox') {

                ArrID = '';
                ArrID = document.getElementById(rowArr[i]).id.split('_');

                jsontext = jsontext + '"' + ArrID[ArrID.length - 1] + '":"' + document.getElementById(rowArr[i]).checked + '",'

            }
            else if (document.getElementById(rowArr[i]).type == 'checkboxlist' || document.getElementById(rowArr[i]).title == 'checkboxlist') {

                var checkboxval = '';

                if (document.getElementById(rowArr[i]) != null) {

                    var cntrl = document.getElementById(rowArr[i]);
                    var checkBoxArray = cntrl.getElementsByTagName("input");

                    for (var j = 0; j < checkBoxArray.length; j++) {

                        if (checkBoxArray[j].checked == true) {

                            checkboxval += "1,";
                        }
                        else {

                            checkboxval += "0,";
                        }
                    }
                    if (checkboxval.length > 1) {

                        checkboxval = checkboxval.substring(0, checkboxval.length - 1);
                    }

                    ArrID = '';
                    ArrID = document.getElementById(rowArr[i]).id.split('_');

                    jsontext = jsontext + '"' + ArrID[ArrID.length - 1] + '":"' + checkboxval + '",'
                }
            }
            else if (document.getElementById(rowArr[i]).type == 'checkboxlistval' || document.getElementById(rowArr[i]).title == 'checkboxlistval') {

                var checkboxvalue = '';

                if (document.getElementById(rowArr[i]) != null) {

                    var cntrl = document.getElementById(rowArr[i]);
                    var checkBoxArray = cntrl.getElementsByTagName("input");

                    for (var j = 0; j < checkBoxArray.length; j++) {

                        if (checkBoxArray[j].checked == true) {

                            checkboxvalue += checkBoxArray[j].parentNode.attributes("someValue").value + ",";
                        }
                    }
                    if (checkboxvalue.length > 1) {

                        checkboxvalue = checkboxvalue.substring(0, checkboxvalue.length - 1);
                    }

                    ArrID = '';
                    ArrID = document.getElementById(rowArr[i]).id.split('_');

                    jsontext = jsontext + '"' + ArrID[ArrID.length - 1] + '":"' + checkboxval + '",'
                }
            }
            else if (document.getElementById(rowArr[i]).type == "select-multiple") {

                ArrID = '';
                ArrID = document.getElementById(rowArr[i]).id.split('_');

                jsontext = jsontext + '"' + ArrID + '":"' + $('#' + rowArr[i]).select2('val').join().replace(',','~') + '",'
            }
            else {
                ArrID = '';
                ArrID = document.getElementById(rowArr[i]).id.split('_');

                var controlVal = document.getElementById(rowArr[i]).value;
                jsontext = jsontext + '"' + ArrID[ArrID.length - 1] + '":"' + RemoveSpecialCharactersForJson(controlVal == 'Search Text' ? '' : controlVal) + '",'
            }
        }
    }
    if (isNULL(AdditionalTracks) != '') {

        var rowAdditionalTracks = new Array();

        if (AdditionalTracks.indexOf('~~') == -1) {
            rowAdditionalTracks[0] = AdditionalTracks;
        }
        else {
            rowAdditionalTracks = AdditionalTracks.split('~~');
        }

        for (i = 0; i < rowAdditionalTracks.length; i++) {

            var rowData = rowAdditionalTracks[i].split('@@');
            jsontext = jsontext + '"' + rowData[0] + '":"' + RemoveSpecialCharactersForJson(rowData[1]) + '",'
        }
    }

    jsontext = jsontext.substring(0, jsontext.length - 1);
    jsontext = jsontext + "}";
    return (jsontext);
}


function RemoveSpecialCharactersForJson(dataString) {
    return (Trim(dataString.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"")));
}

function Trim(str) {
    while (str.charAt(0) == (" ")) {
        str = str.substring(1);
    }
    while (str.charAt(str.length - 1) == " ") {
        str = str.substring(0, str.length - 1);
    }

    return str;
}

function isNULL(strValue) {
    return (strValue == null || strValue == '-null-') ? '' : strValue;
}

function ClientCallbackError() {     // callback error handler event
    //    alert('Error');
    //loadCallback("1");
    show_globalMessage('Request could not proceed.', 'error');
}


function roundNumber(num, dec) {
    num = num * 1.00;
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result.toFixed(2);
}

function emailCheck(strEmail) {
    if ((/^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$/i).test(strEmail)) { return true; } else { return false; }
}

function passwordCheck(strPassword) {
    if ((/^((?=.*\d)(?=.*[A-Z])(?=.*[@#$%]).{8,20})$/i).test(strPassword)) { return true; } else { return false; }
}

function imposeMaxLength(Object, MaxLen) {
    return (Object.value.length <= MaxLen);
}
function detectMaxLength(Event, Object, MaxLen) {
    return (Object.value.length <= MaxLen) || (Event.keyCode == 8 || Event.keyCode == 46 || (Event.keyCode >= 35 && Event.keyCode <= 40))
}


function HidePageElements(ListArr) {

    /// <summary>
    /// Hides (style=display:none) specified elements in the page
    /// </summary>
    /// <param name="ListArr">@ separated control name list eg divEmail@divName</param>

    var ElementList = ListArr.split('@');

    for (i = 0; i < ElementList.length; i++) {

        $('#' + ElementList[i]).hide();

    }
}

function ShowPageElements(ListArr) {

    /// <summary>
    /// Shows (style=display:'') specified elements in the page
    /// </summary>
    /// <param name="ListArr">@ separated control name list eg divEmail@divName</param>

    var ElementList = ListArr.split('@');

    for (i = 0; i < ElementList.length; i++) {

        $('#' + ElementList[i]).show();

    }
}

function validateNumericTxt(txtId) {
    var txtVal = txtId.value;

    if ((isNaN(Trim(txtVal))) || (parseFloat(txtVal) < 0) || (Trim(txtVal) == '')) {
        txtId.value = '';
        return 0;
    }
    else {
        return 1;
    }
}
function imposeMaxLength(Object, MaxLen) {
    return (Object.value.length <= MaxLen);
}

function CheckNumericAndSpecialChars(data) {
    var iChars = "!`@#$%^&*()+=-[]\\\';,./{}1234567890|\":<>?~_";
    var isSuccess = true;
    for (var i = 0; i < data.length; i++) {
        if (iChars.indexOf(data.charAt(i)) != -1) {
            isSuccess = false
            break;
        }
    }
    return isSuccess;
}

function validate_Address_form_Name(data) {

    var isSuccess = true;
    var illegalChars = "!`@#$%^&*()+=-[]\\\';,/{}|\":<>?~_";
    for (var i = 0; i < data.length; i++) {
        if (illegalChars.indexOf(data.charAt(i)) != -1) {
            isSuccess = false;
            break;
        }
    }
    return isSuccess;
}

function validate_Address_form_Phone(data) {

    var isSuccess = true;
    var illegalChars = "!`@#$%^&*()+=[]\\\';,/{}|\":<>?~_";
    for (var i = 0; i < data.length; i++) {
        if (illegalChars.indexOf(data.charAt(i)) != -1) {
            isSuccess = false;
            break;
        }
    }
    return isSuccess;
}

function fn_preventDefault(p_event) {
    if (p_event == undefined) {//FOR IE
        p_event = window.event;
    }
    var key_code;
    if (p_event.keyCode) key_code = p_event.keyCode; //FOR IE
    else if (p_event.which) key_code = p_event.which; //FOR FF,Chrome,safari
    if (key_code == 13) {
        if (p_event.preventDefault != undefined) {
            p_event.preventDefault();
        }
        else {
            p_event.returnValue = false;
        }
    }
    return false;
}


//reset validation by id
function ResetValidator(Id) {
    var validator = document.getElementById(Id);
    validator.isvalid = true;
    ValidatorUpdateDisplay(validator);
    ValidatorValidate(validator);
    return false;
}

function Page_ClientValidateReset() {
    if (typeof (Page_Validators) != "undefined") {
        for (var i = 0; i < Page_Validators.length; i++) {
            var validator = Page_Validators[i];
            validator.isvalid = true;
            ValidatorUpdateDisplay(validator);
        }
    }
}

function fireDefaultButton(event, target) {

    //    var tabindex = document.activeElement.tabIndex;

    //    if (document.getElementById('cmdCancel').tabIndex != tabindex && document.getElementById('btnCancelFooter').tabIndex != tabindex)
    //    {
    if (event.keyCode == 13) {
        var src = event.srcElement || event.target;
        if (!src || (src.tagName.toLowerCase() != "textarea")) {
            var defaultButton;
            if (__nonMSDOMBrowser) {
                defaultButton = document.getElementById(target);
            }
            else {
                defaultButton = document.all[target];
            }
            if (defaultButton && typeof (defaultButton.click) != "undefined") {
                defaultButton.click();
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }
    }
    // }
    return true;
}

function JsCom_fireOnClick(event, target) {
    if (event.keyCode == 13) {
        var src = event.srcElement || event.target;
        if (!src || (src.tagName.toLowerCase() != "textarea")) {
            if (target && typeof (target.click) != "undefined") {
                target.click();
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }
    }
    return true;
}

function fn_ShowDiv(targetDivId) {
    targetDivId = '#' + targetDivId;
    $('#modalBackground').css({ 'width': "100%" });
    $('#modalBackground').css({ 'height': "100%" });
    $('#modalBackground').css({ 'position': 'fixed' });
    $('#modalBackground').css({ 'z-index': '10001' });
    $('#modalBackground').css({ 'background-color': '#d3d4d6' });
    $('#modalBackground').fadeTo('fast', 0.50).show();
    $(targetDivId).css({ 'top': ($(window).height() - $(targetDivId).height() - 35) / 2 + "px" });
    $(targetDivId).css({ 'left': (($(window).width()) - $(targetDivId).width()) / 2 + "px" });
    $(targetDivId).css({ 'z-index': '99999' });
    $(targetDivId).show();
    return false;
}

function fn_HideDiv(targetDivId) {
    targetDivId = '#' + targetDivId;
    $('#modalBackground').css({ 'width': '0px' });
    $('#modalBackground').css({ 'height': '0px' });
    $('#modalBackground').css({ 'position': 'absolute' });
    $('#modalBackground').css({ 'z-index': '1' });
    $('#modalBackground').css({ 'background-color': '#d3d4d6' });
    $(targetDivId).hide();
}

///Insert given array at given position
function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
}

///COMMON FUNCTION TO INTIALIZE NEW TEXT cum DROP-DOWN IN JS ON PAGE LOAD
function fn_initMatchSingleDropDown(varDdlId, varPlaceHolder, varCSPage, varDdlType, varAddParams, preSelectedData, varContentIdS, varIsSelectRequired) {
    //varDdlId = ddlSearchSupplier
    //varPlaceHolder = All Auppliers
    //varCSPage = ServerSide_Processing_List.aspx
    //varDdlType = SUPPLIER
    //varAddParams = Comma Separated Values
    //preSelectedData = selected data on page load
    preSelectedData = ((preSelectedData == null || preSelectedData == '') ? { "id": 0, "text": varPlaceHolder } : preSelectedData)
    if (varDdlId != '') {
        var vUrl = varCSPage + '?Type=' + varDdlType;
        $('#' + varDdlId).select2({
            placeholder: varPlaceHolder,
            minimumInputLength: 0,
            ajax: {
                url: vUrl,
                dataType: 'json',
                data: function (term, page) {
                    return {
                        q: term, // search term  
                        cid: varAddParams,
                        page_limit: 1,
                        nid: varContentIdS
                    };
                },
                results: function (data, page) {
                    if (varIsSelectRequired) {
                        if (preSelectedData.id == '0') {
                            insertArrayAt(data, 0, preSelectedData);
                        }
                        else {
                            insertArrayAt(data, 0, [{ "id": 0, "text": varPlaceHolder }]);
                        }
                    }
                    return { results: data };
                }
            },
            initSelection: function (element, callback) {
                if (preSelectedData != '' && preSelectedData != null) {
                    callback(preSelectedData);
                }
            },
            escapeMarkup: function (m) { return m; }
        }).select2('val', preSelectedData);
    }
}

function fn_initMatchMultipleDropDown(varDdlId, varPlaceHolder, varCSPage, varDdlType, varAddParams, preSelectedData, varContentIdS) {
    //varDdlId = ddlSearchSupplier
    //varPlaceHolder = All Auppliers
    //varCSPage = ServerSide_Processing_List.aspx
    //varDdlType = SUPPLIER
    //varAddParams = Comma Separated Values
    if (varDdlId != '') {
        var vUrl = varCSPage + '?Type=' + varDdlType;
        $('#' + varDdlId).select2({
            placeholder: varPlaceHolder,
            minimumInputLength: 0,
            multiple: true,
            ajax: {
                url: vUrl,
                dataType: 'json',
                data: function (term, page) {
                    return {
                        q: term, // search term  
                        cid: varAddParams,
                        page_limit: 10,
                        nid: varContentIdS
                    };
                },
                results: function (data, page) {
                    return { results: data };
                }
            },
            initSelection: function (element, callback) {
                if (preSelectedData != '' || preSelectedData != null) {
                    callback(preSelectedData);
                }
            },
            escapeMarkup: function (m) { return m; }
        }).select2('val', preSelectedData);
    }
}

function table_searchlist(p_vTableId, p_vAjaxSource, p_vDeleteElementName, p_vContainerDiv, p_vblnIsFirstColumnSort) {
    //    fn_ShowDiv('fixdiv');
    $('#' + p_vTableId).dataTable().fnDestroy();
    var vSortColName = $('#hdnSortingColumnName').val();

    if ('undefined' === typeof p_vblnIsFirstColumnSort || p_vblnIsFirstColumnSort == null || p_vblnIsFirstColumnSort == "") {
        p_vblnIsFirstColumnSort = false;
    }
    //p_vblnIsFirstColumnSort!=null && p_vblnIsFirstColumnSort!=""

    var objTable = $('#' + p_vTableId).dataTable({
        "aoColumnDefs": [{ "bSortable": p_vblnIsFirstColumnSort, "aTargets": [0] }],
        "iDisplayLength": 25,
        "bScrollInfinite": true,
        "bScrollCollapse": true,
        "sScrollY": "500px",
        "scrollX": true,
        "sScrollX": "100%",
        "bProcessing": true,
        "bServerSide": true,
        "bRetrieve": true,
        "bJQueryUI": false,
        //        "bAutoWidth": false,
        //"aoColumns": [{ "sWidth": "30%" }],
        "sAjaxSource": p_vAjaxSource + "&Random=" + Math.random(),
        "sDom": '<"top">rt<"bottom"lp><"clear">',
        "fnServerData": function (sSource, aoData, fnCallback) {
            aoData.push({ "name": "SortCol", "value": $('#hdnSortingColumnName').val() });
            aoData.push({ "name": "SortColType", "value": $('#hdnSortingColumnType').val() });
            $.getJSON(sSource, aoData, function (json) {
                /* Do whatever additional processing you want on the callback, then tell DataTables */
                fnCallback(json);
            });
        },
        "fnDrawCallback": function () {
            fn_HideDiv('fixdiv');
            if (p_vDeleteElementName != undefined)
                fn_StrikethroughDeletedRows(p_vTableId, p_vDeleteElementName);
            //            if (p_vContainerDiv != undefined) {
            //                set_DataTable(p_vContainerDiv);
            //            }
            if (ForceChangePassword == true) {
                fn_ChangePassword();
            }
            fn_HighlightRows(p_vTableId);
        }
    }).fnSetFilteringDelay(searchDelay);
}

function table_detailslist(p_vTableId, p_vAjaxSource, p_vIsDetroy, p_vDeleteElementName, p_vContainerDiv) {
    if (p_vIsDetroy)
        $('#' + p_vTableId).dataTable().fnDestroy();
    var objTable = $('#' + p_vTableId).dataTable({
        "bSort": false,
        "iDisplayLength": 50,
        "bScrollInfinite": true,
        "bScrollCollapse": true,
        "sScrollY": "500px",
        "bProcessing": true,
        "bServerSide": true,
        "bRetrieve": true,
        "bJQueryUI": false,
        "sAjaxSource": p_vAjaxSource + "&Random=" + Math.random(),
        "sDom": '<"top">rt<"bottom"lp><"clear">',
        "fnDrawCallback": function () {
            if (p_vDeleteElementName != undefined)
                fn_StrikethroughDeletedRows(p_vTableId, p_vDeleteElementName);
            //            if (p_vContainerDiv != undefined)
            //                set_DataTable(p_vContainerDiv);
        }
    }).fnSetFilteringDelay(searchDelay);
}

//@@ Function to set Sorting Column name in Hidden Field
function fn_SetSortingColumn(varColumnName, varColumnType) {
    $('#hdnSortingColumnName').val(varColumnName);
    $('#hdnSortingColumnType').val(varColumnType);
    return false;
}

function fn_DatatableProcessingDiv() {
    $('.dataTables_processing').html("<div id='fixdiv'>" + $('#fixdiv').html() + "</div>");
}

jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function (oSettings, iDelay) {
    var _that = this;

    if (iDelay === undefined) {
        iDelay = 250;
    }

    this.each(function (i) {
        $.fn.dataTableExt.iApiIndex = i;
        var
            $this = this,
            oTimerId = null,
            sPreviousSearch = null,
            anControl = $('input', _that.fnSettings().aanFeatures.f);

        anControl.unbind('keyup').bind('keyup', function () {
            var $$this = $this;

            if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
                window.clearTimeout(oTimerId);
                sPreviousSearch = anControl.val();
                oTimerId = window.setTimeout(function () {
                    $.fn.dataTableExt.iApiIndex = i;
                    _that.fnFilter(anControl.val());
                }, iDelay);
            }
        });

        return this;
    });
    return this;
};

function fnGetSelectedRow(datatable, objID) {
    var aReturn = new Array();
    var aTrs = datatable.fnGetNodes();

    for (var i = 0; i < aTrs.length; i++) {
        if ($(aTrs[i]).html().indexOf(objID) != -1) {
            return $(aTrs[i]);
        }
    }
    return null;
}
//@@@ Show global message
//@@@ message : Message to be display
//@@@ track : Error, warning,information alert track to add style
function show_globalMessage(msg, track) {
    var n = noty({
        layout: 'top',
        theme: 'defaultTheme',
        type: (track == 'info' ? 'success' : 'error'),
        text: msg, // can be html or string
        dismissQueue: false, // If you want to use queue feature set this true
        template: '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
        animation: {
            open: { height: 'toggle' },
            close: { height: 'toggle' },
            easing: 'swing',
            speed: 500 // opening & closing animation speed
        },
        timeout: false, //messageTimeout, // delay for closing event. Set false for sticky notifications
        force: true, // adds notification to the beginning of queue when set to true
        modal: false,
        maxVisible: 1, // you can set max visible notification for dismissQueue true option,
        killer: true, // for close all notifications before show
        closeWith: ['button'], // ['click', 'button', 'hover', 'backdrop'] // backdrop click will close all open notifications
        callback: {
            onShow: function () { },
            afterShow: function () { },
            onClose: function () { },
            afterClose: function () { }
        },
        //        buttons: false // an array of buttons
        buttons: [
		{
		    addClass: 'noty_close_button',
		    text: '<i class="fa fa-times"></i>',
		    onClick: function ($noty) {
		        $noty.close();
		    }
		}
        ]
    });
    console.log('html: ' + n.options.id);
}

function fn_ConfirmProcedure() {
    var n = noty({
        layout: 'center',
        theme: 'defaultTheme',
        type: 'confirm',
        text: 'As there are some pending items in the checklist, do you still want to create a new invoice ?',
        buttons: [
		{
		    addClass: 'noty_confirmbuttons btn-primary', text: 'Ok', onClick: function ($noty) {
		        $noty.close();
		        return fn_ValidationClientDet(0, true);
		    }
		},
		{
		    addClass: 'noty_confirmbuttons btn-primary', text: 'Cancel', onClick: function ($noty) {
		        $noty.close();
		        return fn_ValidationClientDet(1, false);
		    }
		}
        ]
    });
    console.log('html: ' + n.options.id);
}

function show_globalDiv(track) {
    $('#globaldiv').css('top', $(window).scrollTop() + 'px');
    $('#globaldiv').css('z-index', '999999');
    $('#globaldiv').css('position', 'fixed');
    $('#globaldiv').fadeTo('slow', 0.99).show();
    if (track == 'info') {
        setTimeout("hide_globalDiv()", messageTimeout);
    }
}

function hide_globalDiv() {
    $('#globaldiv').hide();
    $('#spnGlobalMessage').html('');
}

function fn_StrikethroughDeletedRows(p_TableName, p_ElementName) {
    var vStatus = document.getElementsByName(p_ElementName);
    if (vStatus.length > 0) {
        for (var i = 0; i < vStatus.length; i++) {
            if (vStatus[i].value == "2") {
                var vRowElementId = vStatus[i].id;
                var row = fnGetSelectedRow($('#' + p_TableName).dataTable(), vRowElementId);
                $(row).addClass('strikeout');
                $(row).find('a').addClass('hide');
                $(row).find('input').attr('disabled', true);
            }
        }
    }
}

function fn_StrikethroughSingleRow(p_TableName, p_ElementID) {
    $('#' + p_ElementID).val("2");
    var row = fnGetSelectedRow($('#' + p_TableName).dataTable(), p_ElementID);
    $(row).addClass('strikeout');
    $(row).find('a').addClass('hide');
    $(row).find('input').attr('disabled', true);
}

//@@@ Return javascript datetime object from dd/mm/yyyy string date
function fn_ConvertToDate(p_strDate) {
    var dateParts = p_strDate.split('/');
    var returnDate = new Date(dateParts[2], parseInt(dateParts[1]) - 1, dateParts[0], 0, 0, 0, 0);
    return returnDate;
}

function clearDates(oEvent) {
    if (!oEvent) { oEvent = window.event; } //check for the proper location of the event object
    var iKeyCode = oEvent.keyCode;
    if (iKeyCode == 8 || iKeyCode == 46) {
        var oTarget = oEvent.target || oEvent.srcElement;
        oTarget.value = '';
    }
    if (iKeyCode != 9) {
        return false;
    }
    else {
        return true;
    }
}

function clearValidatorDates(oEvent, validatorList) {
    if (!oEvent) { oEvent = window.event; } //check for the proper location of the event object
    var iKeyCode = oEvent.keyCode;
    if (iKeyCode == 8 || iKeyCode == 46) {
        var oTarget = oEvent.target || oEvent.srcElement;
        oTarget.value = '';
    }
    if (validatorList != undefined && validatorList != '') {
        arrValidator = validatorList.split('@');
        for (i = 0; i < arrValidator.length; i++) {
            ResetValidator(arrValidator[i]);
        }
    }
    if (iKeyCode != 9) {
        return false;
    }
    else {
        return iKeyCode;
    }
}

function checkIsNumeric(cntrl) {

    var numbers = /^(\d(,)?)*(.\d*)?$/;
    if (cntrl.value != '') {
        if (cntrl.value.match(numbers)) {
            var decimaTwoPlace = /^\d+(\.\d{1,2})?$/;
            if (!cntrl.value.match(decimaTwoPlace)) {
                var v = parseFloat(cntrl.value);
                cntrl.value = fn_RoundValue(v, 2);
                return true;
            }
            else {
                return true;
            }
        }
        else {
            cntrl.value = '0';
            return false;
        }
    }
    else {
        cntrl.value = '0';
        return true;
    }
}

///Function to get Round of value

function fn_RoundValue(value, decimal) {
    if (decimal == 0) {
        return Math.round(value);
    }
    else {
        var factor = 1;
        for (var i = 1; i <= decimal; i++) {

            factor = factor * 10;

        }

        return Math.round(value * factor) / factor;

    }

}




//@@@ Set datable width
function set_DataTable(p_id) {
    var thCount = 0;
    var arrTh = new Array();
    var cntrID = '#' + p_id;
    //@@@ Set scroller header attributes
    $(cntrID).find('.dataTables_scrollHead').each(function () {
        $(this).css({ 'width': '100%' });
        $(this).find('.dataTables_scrollHeadInner').each(function () {
            $(this).css({ 'width': '100%' });
            $(this).find('table').each(function () {
                $(this).css({ 'width': '97.7%' });
                $(this).find('th').each(function () {
                    var currCol = $(this);
                    var len = $(this).find('.len').each(function () {
                        var p_width = $(this).attr('length');
                        arrTh[thCount] = p_width;
                        currCol.css({ 'width': p_width });
                        thCount = thCount + 1;
                    }); //len
                }); //th
            }); //table
        }); //.dataTables_scrollHeadInner
    }); //.dataTables_scrollHead

    //@@@ Set body header attributes
    var cntCol = 0;
    $(cntrID).find('.dataTables_scrollBody').each(function () {
        $(this).css({ 'width': '97.7%' });
        $(this).find('th').each(function () {
            var Col = $(this);
            $(this).css({ 'width': arrTh[cntCol] });
            cntCol = cntCol + 1;
        }); //th
    });  //.dataTables_scrollBody 

    //@@@ Set body column attributes
    var tdCol = 0;

    $(cntrID).find('.dataTables_scrollBody').each(function () {
        $(this).css({ 'width': '97.7%' });
        $(this).find('table').each(function () {
            $(this).find('tr').each(function () {
                tdCol = 0;
                $(this).find('td').each(function () {
                    var Col = $(this);
                    $(this).css({ 'width': arrTh[tdCol] });
                    tdCol = tdCol + 1;
                    $(this).find('label').each(function () {
                        $(this).css({ 'width': '99%' });
                    }); //label

                }); //td
            }); //tr
        }); //table
    });       //.dataTables_scrollBody

}

//@@@ Open pop calender control
function show_DateCalender(p_vObjectId) {
    if (p_vObjectId != undefined)
        $('#' + p_vObjectId).datepicker('show');
}
function fn_HighlightRows(p_objTable) {
    var AllRows = document.getElementsByClassName('hdnHighlightCell');
    if (AllRows != null && AllRows != undefined && AllRows.length > 0) {
        for (var i = 0; i < AllRows.length; i++) {
            if (AllRows[i].value != "none") {
                var vRowElementId = AllRows[i].id;
                var highlightrow = fnGetSelectedRow($('#' + p_objTable).dataTable(), vRowElementId);
                $('td:eq(1)', $(highlightrow)).css("background-color", "#FF0000").css('color', '#FFFFFF');
            }
        }
    }
}

function RegisterHTMLEditor(selector, editor_width, editor_height, page) {
    //    tinymce.init({
    //        menubar: false, statusbar: false,
    //        browser_spellcheck: true,
    //        selector: selector,
    //        theme: "modern",
    //        width: editor_width,
    //        height: editor_height,
    //        //forced_root_block: 'p',
    //        nonbreaking_force_tab: true,
    //        //invalid_elements: "span",
    //        //inline_styles: true,
    //        //table_default_border: "1",
    //        plugins: [
    //         "advlist autolink lists hr anchor pagebreak spellchecker",
    //         "searchreplace wordcount visualblocks visualchars code insertdatetime media nonbreaking ",
    //         "save table directionality emoticons template paste textcolor"
    //   ],
    //        content_css: "../tinymce/tinymce_style.css",
    //        toolbar: "undo redo | cut  copy  paste | bold italic underline strikethrough | fontselect fontsizeselect | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor backcolor | table | code ",

    //        style_formats: [
    //            { title: 'Calibri', inline: 'span', styles: { 'font-family': 'Calibri'} },
    //            { title: 'Open Sans', inline: 'span', styles: { 'font-family': 'Open Sans'} },
    //            { title: 'Arial', inline: 'span', styles: { 'font-family': 'arial'} },
    //            { title: 'Book Antiqua', inline: 'span', styles: { 'font-family': 'book antiqua'} },
    //            { title: 'Comic Sans MS', inline: 'span', styles: { 'font-family': 'comic sans ms,sans-serif'} },
    //            { title: 'Courier New', inline: 'span', styles: { 'font-family': 'courier new,courier'} },
    //            { title: 'Georgia', inline: 'span', styles: { 'font-family': 'georgia,palatino'} },
    //            { title: 'Helvetica', inline: 'span', styles: { 'font-family': 'helvetica'} },
    //            { title: 'Impact', inline: 'span', styles: { 'font-family': 'impact,chicago'} },
    //            { title: 'Symbol', inline: 'span', styles: { 'font-family': 'symbol'} },
    //            { title: 'Tahoma', inline: 'span', styles: { 'font-family': 'tahoma'} },
    //            { title: 'Terminal', inline: 'span', styles: { 'font-family': 'terminal,monaco'} },
    //            { title: 'Times New Roman', inline: 'span', styles: { 'font-family': 'times new roman,times'} },
    //            { title: 'Verdana', inline: 'span', styles: { 'font-family': 'Verdana'} }
    //        ],

    //        setup: function (ed) {
    //            ed.on("init", function (ed) {
    //                this.getDoc().body.style.fontSize = '12pt';
    //                this.getDoc().body.innerHTML = this.getDoc().body.innerHTML.replace("<div><span style=\"color: #000000;\" data-mce-style=\"color: #000000;\">Untitled document</span></div>", "");
    //            });
    //        }

    //    });
    tinymce.init({
        menubar: false, statusbar: false,
        browser_spellcheck: true,
        selector: selector,
        theme: "modern",
        width: editor_width,
        height: editor_height,
        nonbreaking_force_tab: true,
        plugins: [
        "advlist autolink lists link image hr anchor",
        "searchreplace wordcount visualblocks visualchars code",
        "insertdatetime media nonbreaking save table directionality",
        "emoticons template paste textcolor colorpicker textpattern"
        ],
        toolbar: "undo redo | cut  copy  paste | bold italic underline strikethrough | fontsizeselect | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor backcolor | table | code",

        setup: function (ed) {
            ed.on("init", function (ed) {
                this.getDoc().body.style.fontSize = '12pt';
                this.getDoc().body.style.fontFamily = 'Calibri';
                this.getDoc().body.innerHTML = this.getDoc().body.innerHTML.replace("<div><span style=\"color: #000000;\" data-mce-style=\"color: #000000;\">Untitled document</span></div>", "");
            });
        }
    });
}

////@@Compare Two Month and Year
function customParse(str) {
    var months = ['01', '02', '03', '04', '05', '06',
             '07', '08', '09', '10', '11', '12'],
   n = months.length, re = /(\d{2})\/([0-9]{2})\/(\d{4})/i, matches;

    while (n--) { months[months[n]] = n; } // map month names to their index :)

    matches = str.match(re); // extract date parts from string

    return new Date(matches[3], months[matches[2]], matches[1]);
}

function jsCom_CompareDate(date1, date2) {
    if (date1 != "" && date2 != "") {
        var dt1 = date1;
        var dt2 = date2;
        if (customParse(dt1) > customParse(dt2)) {
            return false;
        }
        else {
            return true;
        }
    }
    return true;
}

function jsCom_CompareCustomDate(date1, date2, diff) {
    if (date1 != "" && date2 != "") {
        var newDate1 = customParse(date1);
        newDate1.setDate(newDate1.getDate() + parseInt(diff));
        var newDate2 = customParse(date2);
        if (newDate1 > newDate2) {
            return false;
        }
        else {
            return true;
        }
    }
    return true;
}

function getMonthNumber(Month, type) {
    //parameter Month should be int and type is fullname or shortName
    //
    var FullMonthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"];
    var ShortMonthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    if (type == "Full") {
        for (var i = 0; i < FullMonthNames.length; i++) {
            if (FullMonthNames[i].toString().toLowerCase() == Month.toString().toLowerCase()) {
                if ((i + 1).toString().length > 1)
                    return i + 1;
                else
                    return '0' + (i + 1);
            }
        }
    }
    else
        if (type == "Short") {
            for (var i = 0; i < ShortMonthNames.length; i++) {
                if (ShortMonthNames[i].toString().toLowerCase() == Month.toString().toLowerCase()) {
                    return i + 1;
                }
            }
        }

}

//Use This Function to Sort date of Format dd-MMM-yyyy or dd/MMM/yyyy
function dhtmlx_g_ShortDate_customSort(a, b, order) {
    a = a.replace(/-/g, '/').replace(/ /g, '/').split("/");
    b = b.replace(/-/g, '/').replace(/ /g, '/').split("/");
    if (a == '' || a == null)
        a = [0, 0, 0];
    if (b == '' || b == null)
        b = [0, 0, 0];
    if (a[2] == b[2]) {
        var a1 = getMonthNumber(a[1], 'Short');
        var b1 = getMonthNumber(b[1], 'Short');
        if (a1 == b1)
            return (a[0] > b[0] ? 1 : -1) * (order == "asc" ? 1 : -1);
        else
            return (a1 > b1 ? 1 : -1) * (order == "asc" ? 1 : -1);
    } else
        return (a[2] > b[2] ? 1 : -1) * (order == "asc" ? 1 : -1);
}

//Use This Function to Sort funancial year column
function dhtmlx_g_FinancialYear_customSort(a, b, order) {
    fy1 = a.split("-");
    fy2 = b.split("-");
    fy11 = parseInt(fy1[0].trim());
    fy12 = parseInt(fy1[1].trim());
    fy21 = parseInt(fy2[0].trim());
    fy22 = parseInt(fy2[1].trim());

    if (order == "asc")
        return fy11 > fy21 ? 1 : -1;
    else
        return fy11 < fy21 ? 1 : -1;
}

//Use This Functions to Sort date of Format dd-MM-yyyy or dd/MM/yyyy
function dhtmlx_g_date_customSort(a, b, order) {

    a = a.replace(/-/g, '/').split("/");
    b = b.replace(/-/g, '/').split("/");
    if (a == '' || a == null)
        a = [0, 0, 0];
    if (b == '' || b == null)
        b = [0, 0, 0];
    if (a[2] == b[2]) {
        if (a[1] == b[1])
            return (a[0] > b[0] ? 1 : -1) * (order == "asc" ? 1 : -1);
        else
            return (a[1] > b[1] ? 1 : -1) * (order == "asc" ? 1 : -1);
    } else
        return (a[2] > b[2] ? 1 : -1) * (order == "asc" ? 1 : -1);
}
var monthshortNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
//Use This Functions to Sort month year Format MMM-yyyy
function dhtmlx_g_MonthYear_customSort(a, b, order) {

    a = a.replace(/-/g, '/').split("/");
    b = b.replace(/-/g, '/').split("/");
    if (a == '' || a == null)
        a = [0, 0];
    if (b == '' || b == null)
        b = [0, 0];

    if (a[1] == b[1])
        return (monthshortNames.indexOf(a[0]) > monthshortNames.indexOf(b[0]) ? 1 : -1) * (order == "asc" ? 1 : -1);
    else
        return (a[1] > b[1] ? 1 : -1) * (order == "asc" ? 1 : -1);
}

//Use This Functions to Sort String Columns
function dhtmlx_g_string_customSort(a, b, order) {
    return (a.toLowerCase() > b.toLowerCase() ? 1 : -1) * (order == "asc" ? 1 : -1);
}

//Use This Functions to Sort grid checkboxes
function dhtmlx_g_checkbox_customSort(a, b, order) {
    var retVal = 1;
    if (a == '') {
        retVal = 1;
    }
    else {
        if (a == '0') {
            if (b == '') {
                retVal = -1;
            }
            else {
                retVal = 1;
            }
        }
        else { //a=='1'
            if (b != '1') {
                retVal = -1;
            }
            else {
                retVal = 1;
            }
        }
    }
    return retVal * (order == "asc" ? 1 : -1);
}

//USe this function to sort comma separated amount
function dhtmlx_g_Amount_customSort(a, b, order) {
    var n = parseFloat(a.replace(/,/g, ''));
    var m = parseFloat(b.replace(/,/g, ''));
    if (order == "asc")
        return n > m ? 1 : -1;
    else
        return n < m ? 1 : -1;
}

//=============== div expand collapse functions =================================

function fn_Accordion(strRowID, p_vTrack) {//p_vTrack => 1 = Open Div, 0 = Close Div
    var vExpandCollapseLink = $('.expandcollapse');
    if (p_vTrack == 1) {
        $('.SubCategory').addClass('hidden');
        $('#category_' + strRowID).removeClass('hidden');
        $('.fa-minus-square-o').removeClass('fa-minus-square-o').addClass('fa-plus-square');
        $('#icon_' + strRowID).removeClass('fa-plus-square').addClass('fa-minus-square-o');
        for (var i = 0; i < vExpandCollapseLink.length; i++) {
            var vObjectID = vExpandCollapseLink[i].id.split('_');
            $(vExpandCollapseLink[i]).removeAttr('onclick').attr("onclick", "return fn_Accordion(" + vObjectID[1] + ", 1)").removeAttr('title').attr("title", "Expand");
        }
        $('#lnk_' + strRowID).removeAttr('onclick').attr("onclick", "return fn_Accordion(" + strRowID + ", 0)").removeAttr('title').attr("title", "Collapse");
    }
    else {
        $('#category_' + strRowID).addClass('hidden');
        $('#icon_' + strRowID).removeClass('fa-minus-square-o').addClass('fa-plus-square');
        //        for (var i = 0; i < vExpandCollapseLink.length; i++) {
        //            var vObjectID = vExpandCollapseLink[i].id.split('_');
        //            $(vExpandCollapseLink[i]).removeAttr('onclick').attr("onclick", "return fn_Accordion(" + vObjectID[1] + ", 0)").removeAttr('title').attr("title", "Collapse");
        //        }
        $('#lnk_' + strRowID).attr("onclick", "return fn_Accordion(" + strRowID + ", 1)").removeAttr('title').attr("title", "Expand");
    }

    $('#iconCollapse').removeClass('fa-plus-square').removeClass('fa-minus-square-o').addClass('fa-minus-square-o');
    $('#iconExpand').removeClass('fa-minus-square-o').removeClass('fa-plus-square').addClass('fa-plus-square');
}

function fn_ExpandCollapseAll(p_vTrack) {//p_vTrack => 1 = Expand all, 0 = Collapse all
    var vExpandCollapseLink = $('.expandcollapse');
    if (p_vTrack == 1) {
        $('.SubCategory').removeClass('hidden');
        for (var i = 0; i < vExpandCollapseLink.length; i++) {
            var vObjectID = vExpandCollapseLink[i].id.split('_');
            $(vExpandCollapseLink[i]).removeAttr('onclick').attr("onclick", "return fn_Accordion(" + vObjectID[1] + ", 0)").removeAttr('title').attr("title", "Collapse");
        }
        $('.fa-plus-square').removeClass('fa-plus-square').addClass('fa-minus-square-o');
    }
    else {
        $('.SubCategory').addClass('hidden');
        for (var i = 0; i < vExpandCollapseLink.length; i++) {
            var vObjectID = vExpandCollapseLink[i].id.split('_');
            $(vExpandCollapseLink[i]).removeAttr('onclick').attr("onclick", "return fn_Accordion(" + vObjectID[1] + ", 1)").removeAttr('title').attr("title", "Expand");
        }
        $('.fa-minus-square-o').removeClass('fa-minus-square-o').addClass('fa-plus-square');
    }

    $('#iconCollapse').removeClass('fa-plus-square').removeClass('fa-minus-square-o').addClass('fa-minus-square-o');
    $('#iconExpand').removeClass('fa-minus-square-o').removeClass('fa-plus-square').addClass('fa-plus-square');
}
//=============== End div expand collapse functions =================================

/*************** Disable save button ******************/
function fn_DisableSaveButtons(p_vValidationGroup, p_vButtonList) {
    if (Page_ClientValidate(p_vValidationGroup)) {
        if (p_vButtonList.indexOf('§')) {
            var vButtonList = p_vButtonList.split('§');
            for (var i = 0; i < vButtonList.length; i++) {
                $('#' + vButtonList[i]).removeAttr('onclick').removeClass('btn-primary').addClass('btn-secondary');
            }
        }
        else {
            $('#' + p_vButtonList).removeAttr('onclick').removeClass('btn-primary').addClass('btn-secondary');
        }
        return true;
    }
    else
        return false;
}
/*************** Disable save button ******************/

/*************** Disable button ******************/
function fn_DisableButtons(p_vButtonList) {
    if (p_vButtonList.indexOf('§')) {
        var vButtonList = p_vButtonList.split('§');
        for (var i = 0; i < vButtonList.length; i++) {
            $('#' + vButtonList[i]).removeAttr('onclick').removeClass('btn-primary').addClass('btn-secondary');
        }
    }
    else {
        $('#' + p_vButtonList).removeAttr('onclick').removeClass('btn-primary').addClass('btn-secondary');
    }
}
/*************** Disable save button ******************/

/*************** ValidateExpression *******************/

function fn_ValidateExpressionTextbox(p_obj, p_args) {
    p_args.IsValid = true;
    var varCntl = $("#" + p_obj.controltovalidate);
    if (varCntl.val() != "") {
        var vValidation = fn_ValidateExpression(varCntl.val(), $(p_obj).attr("expressionid"));
        if (vValidation != "") {
            p_args.IsValid = false;
            p_obj.childNodes['0'].innerHTML = vValidation;
        }
    }
    return p_args.IsValid;
}
function fn_ValidateExpression(p_ValToValidate, p_OptVal) {

    var strRegularExpression;
    var strErrorMsg;
    switch (p_OptVal) {
        case "Num":
            {
                strRegularExpression = new RegExp(/^([0-9']+\s*)+$/); // Only Numbers
                strErrorMsg = "Enter only numbers.";
                break;
            }
        case "AlpNum":
            {
                strRegularExpression = new RegExp(/^([a-zA-Z0-9']+\s*)+$/);  // alphabets and Numbers with white space are valid
                strErrorMsg = "Enter only alphabets and numbers.";
                break;
            }
        case "Alp":
            {
                strRegularExpression = new RegExp(/^([a-zA-Z']+\s*)+$/); // Alphabet Only
                strErrorMsg = "Enter only alphabets.";
                break;
            }
        case "NumDel":
            {
                strRegularExpression = new RegExp(/^[0-9]+([\,\.][0-9]+)?$/g); // Only decimal
                strErrorMsg = "Enter only numbers or decimal numbers.";
                break;
            }
        case "AlpNumSplChar":
            {

                strRegularExpression = new RegExp(/^([a-zA-Z0-9-.\/#\s&@,:;'\\_()\’\?])+$/); // Alphabet Numbers and Some special characters
                strErrorMsg = "Only alphabets, numeric and specific special characters (-, (, ), # , &, @, ;, ', /, \, _, ? and :) are allowed.";
                break;
            }
        case "NumWithPlusMinus":
            {
                strRegularExpression = new RegExp(/^([0-9'+\-]+\s*)+$/); // Only Numbers and - and  +
                strErrorMsg = "Only numerics, - and + are allowed.";
                break;
            }
        case "Num&SplChars":
            {
                strRegularExpression = new RegExp(/^([0-9'+\-\/]+\s*)+$/); // Only Numbers and some special characters
                strErrorMsg = "Only numerics, -, + and / are allowed.";
                break;
            }
        case "Phone&Fax":
            {
                strRegularExpression = new RegExp(/^([0-9'+\-\/\(\)]+\s*)+$/); // Only Numbers and some special characters for fax no
                strErrorMsg = "Only numerics, -, +, /,( and ) are allowed.";
                break;
            } 
        case "NumDelMinus":
            {
                strRegularExpression = new RegExp(/^[0-9'+\-]+([\,\.][0-9]+)?$/g); // Only decimal
                strErrorMsg = "Enter only numbers or decimal numbers.";
                break;
            }
        case "Email":
            {
                strRegularExpression = new RegExp(/^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$/i); // Email Validations
                strErrorMsg = "Enter valid email id.";
                break;
            }
    }

    var flagSuccess = strRegularExpression.test(p_ValToValidate);

    if (flagSuccess == false)
        return strErrorMsg;
    else
        return "";
}

//======================== Master callback =================================

function fn_SaveChangePassword() {
    if (Page_ClientValidate("vgChangePassword")) {
        $('#btnChangePassword').attr('disabled', true);
        masterCallBack('ChangePassword', 'txtNewPassword', '');
    }

    return false;
}

function fn_ChangePassword() {
    $('#txtNewPassword').val("");
    $('#txtConfirmNewPassword').val("");
    $('#btnChangePassword').attr('disabled', false);
    Page_ClientValidateReset();
    if (ForceChangePassword == true) {
        var objCloseBtn = $('.ui-dialog-titlebar-close');
        $(objCloseBtn).css("visibility", 'hidden');
    }
    else {
        var objCloseBtn = $('.ui-dialog-titlebar-close');
        $(objCloseBtn).css("visibility", 'visible');
    }
    $('#divChangePassword').dialog('open');
}

//@@@ Callback response function
function masterGetResponse(returnVal) {
    try {
        hideLoader(returnVal);
        var objResult = $.parseJSON(returnVal);
        if (objResult.SessionTimeOut == "1") {
            window.location.href = "login.aspx";
        }
        else {
            if (objResult.Track == 'ChangePassword') {
                if (objResult.IsSuccess == "1") {
                    ForceChangePassword = false;
                    show_globalMessage('Password changed successfully.', 'info');
                    setTimeout("$('#divChangePassword').dialog('close');", messageTimeout);


                }
                else {
                    $('#btnChangePassword').removeAttr('disabled');
                    show_globalMessage("Could not change the password. Try again.", 'error');
                }
            }
        }
    }
    catch (ex) {
        alert('Error : ' + ex.message);
    }
}

function fn_RegExpValidatorNewPassword(p_obj, p_args) {
    p_args.IsValid = true;
    var NewPassword = document.getElementById('txtNewPassword').value;
    if (NewPassword != '') {
        var strRet = fn_ValidateExpression(NewPassword, '5');

        if (strRet != '') {
            var span = document.getElementById("spnNewPassword");
            span.textContent = strRet;
            $('#spnNewPassword').show();
            p_args.IsValid = false;
        }
    }

}

///@Startdate must be in dd/mm/yyyy format
function fn_SetIncreamentTo_OneYear(Startdate) {

    var integerArray = Startdate.split("/");
    var myDate = new Date(integerArray[2], integerArray[1] - 1, integerArray[0]);

    var increamentoneYear = new Date(new Date(myDate).setMonth(myDate.getMonth() + 12));
    increamentoneYear.setDate(increamentoneYear.getDate() - 1);


    return increamentoneYear;

}


//Get scroll postion
function fn_GetScrollPostion() {
    try {
        m_CallBackWindowScrollPosition = $(window).scrollTop();
    }
    catch (e) {
    }
}

//Set Scroll position
function fn_SetScrollPostion() {
    try {
        $(window).scrollTop(m_CallBackWindowScrollPosition);
    }
    catch (e) {
    }
}

//Comma separated Number Format
function fn_GetCommaSeparatedFormat(p_vValue) {
    return p_vValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function setMultipleComboSelectedValue(selID, control) {
    var arrSelID = selID.split(',');
    var obj = document.getElementById(control);
    for (var j = 0; j < arrSelID.length; j++) {
        //obj.value = arrSelID[j];

        for (var i = 0; i < obj.options.length; i++) {
            if (obj.options[i].value == arrSelID[j]) {
                obj.options[i].selected = true;
                break;
            }
        }
    }
    $('.chzn-select').trigger("liszt:updated");
}

//Clear All Controls 

function clear_form_elements(id_name) {

    jQuery("#" + id_name).find(':input').each(function () {
        switch (this.type) {
            case 'password':
            case 'text':
                jQuery(this).val('');
                $(this).select2('val', $(this).find(':selected').val());
                break;
            case 'textarea':
            case 'file':
                jQuery(this).val('');
                break;
            case 'select-one':
            case 'select-multiple':
                $(this).select2("val", "");
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
            case 'label':
                jQuery(this).val('');
                break;
        }
    });
    Page_ClientValidate('');


    //    var select = document.getElementById('cboEmployee');
    //    alert(select.type);
}

function clear_form_elements_ForTab(e, divID) {
    if (e.keyCode == 13) {
        clear_form_elements(divID);
        // return false;
    }
}

function fn_ClearAllValidations(objParentControl)
{
    
}
